<template>
  <div class="equipment-things-wrap">
    <div class="search-wrap">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.native.prevent>
        <el-form-item v-if="$store.state.userinfo.isMuilUnitUser === 1">
          <el-select filterable @change="orgIdChange" v-model="searchForm.orgIds" placeholder="请选择业主单位">
            <el-option
              v-for="item in orgOptions"
              :key="item.organizationId"
              :label="item.shortName"
              :value="item.organizationId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="categoryId">
          <tree-select
            v-model="searchForm.categoryId"
            placeholder="请选择物联设备类别"
            filterable
            :width="200"
            :data="typeList"
            :defaultProps="typeDefaultProps"
            :checkedKeys="defaultCheckedCategoryId"
            :nodeKey="typeNodeKey"
            @node-click="handleNodeClick"
          ></tree-select>
        </el-form-item>
        <el-form-item prop="fbsId" v-show="String(searchForm.orgIds).split(',').length === 1">
          <tree-select
            v-model="searchForm.fbsId"
            placeholder="请选择所在建筑物"
            filterable
            :width="200"
            :data="buildList"
            :defaultProps="buildDefaultProps"
            :checkedKeys="defaultCheckedFbsId"
            :nodeKey="buildNodeKey"
          ></tree-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            auto-complete="off"
            placeholder="请输入搜索内容"
            clearable
            @keyup.enter.native="search"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="form-search-btn" type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- <div class="more-btns">
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">更多操作</span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="export">按当前条件导出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>-->
    </div>

    <el-row class="overclick-wrap" :gutter="40">
      <el-col :span="4">
        <div class="item-wrap" @click="searchForm.fireTType = -1" :class="searchForm.fireTType == -1 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-4">{{ equipmentStatistics.count }}</p>
            <p class="item-title">物联设备总数（个）</p>
          </div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="item-wrap" @click="searchForm.fireTType = 0" :class="searchForm.fireTType == 0 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-3">{{ equipmentStatistics.normalCount }}</p>
            <p class="item-title">正常（个）</p>
          </div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="item-wrap" @click="searchForm.fireTType = 10" :class="searchForm.fireTType == 10 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-1">{{ equipmentStatistics.fireAlarmCount }}</p>
            <p class="item-title">报警（个）</p>
          </div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="item-wrap" @click="searchForm.fireTType = 20" :class="searchForm.fireTType == 20 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-2">{{ equipmentStatistics.faultAlarmCount }}</p>
            <p class="item-title">故障（个）</p>
          </div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="item-wrap" @click="searchForm.fireTType = 40" :class="searchForm.fireTType == 40 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-5">{{ equipmentStatistics.linkageAlarmCount }}</p>
            <p class="item-title">联动（个）</p>
          </div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="item-wrap" @click="searchForm.fireTType = 30" :class="searchForm.fireTType == 30 ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-8">{{ equipmentStatistics.shieldAlarmCount }}</p>
            <p class="item-title">屏蔽（个）</p>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-table v-loading="loading" ref="equipmentThingsTableList" :data="tableData" style="width: 100%">
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column
        v-if="$store.state.userinfo.isMuilUnitUser === 1"
        label="业主单位"
        prop="organizationName"
        width="150"
      ></el-table-column>
      <el-table-column label="图片" prop="categoryPicUrl" width="120">
        <template v-if="scope.row.categoryPicUrl != ''" slot-scope="scope">
          <img
            :src="scope.row.categoryPicUrl.split(',')[0]"
            width="50px"
            height="50px"
            @click="$imgPreview"
            :data-imgpreview="scope.row.categoryPicUrl"
          />
        </template>
      </el-table-column>
      <el-table-column label="消防系统" prop="fireSystemName" width="200"></el-table-column>
      <el-table-column label="物联设备类别" prop="categoryName" width="200"></el-table-column>
      <el-table-column label="名称" prop="name">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
          <el-tag
            size="small"
            v-if="
              scope.row.elevatorStatus === 2 || scope.row.elevatorStatus === 3
            "
            :type="scope.row.elevatorStatus === 2 ? 'warning' : 'danger'"
          >
            梯控{{
            scope.row.elevatorStatus === 2
            ? "触发"
            : scope.row.elevatorStatus === 3
            ? "已禁用"
            : ""
            }}
            <el-button
              type="text"
              size="mini"
              style="padding: 5px 0"
              v-if="
                scope.row.elevatorStatus === 2 || scope.row.elevatorStatus === 3
              "
              @click="handleElevator(scope.row)"
            >
              {{
              scope.row.elevatorStatus === 2
              ? "禁用"
              : scope.row.elevatorStatus === 3
              ? "修改"
              : ""
              }}
            </el-button>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="位置" prop="detailLocation">
        <template slot-scope="scope">
          <el-link type="primary" @click="openPosition(scope.row)">
            {{
            scope.row.detailLocation
            }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="实时监测状态" prop="realTimeStatusName" width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.realTimeStatus == 0" class="type-tags type-color-3">{{ scope.row.realTimeStatusName }}</div>
          <div
            v-else-if="scope.row.realTimeStatus == 10"
            class="type-tags type-color-1"
          >{{ scope.row.realTimeStatusName }}</div>
          <div
            v-else-if="scope.row.realTimeStatus == 20"
            class="type-tags type-color-2"
          >{{ scope.row.realTimeStatusName }}</div>
          <div
            v-else-if="scope.row.realTimeStatus == 40"
            class="type-tags type-color-5"
          >{{ scope.row.realTimeStatusName }}</div>
          <div v-else class="type-tags type-color-8">{{ scope.row.realTimeStatusName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="监测值" prop="analogList">
        <template slot-scope="scope">
          <p
            v-for="item in scope.row.analogList"
            :key="item.id"
          >{{ item.dataTypeName + "：" + item.analogValue + item.analogUnits }}</p>
        </template>
      </el-table-column>
      <el-table-column label="附近监控" prop="videoList">
        <template slot-scope="scope">
          <span v-if="scope.row.videoList && scope.row.videoList.length > 0">
            <el-link
              type="primary"
              v-for="(item, i) in scope.row.videoList"
              :key="i"
              @click="openMonitor(scope.row,item)"
            >
              {{
              item.name + (scope.row.videoList.length > i + 1 ? "、" : "")
              }}
            </el-link>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="handleDetail(scope.row)" type="text" size="small">详情</el-button>
          <el-button v-if="mockEquips.find(n=>{return n.id==scope.row.id})" :disabled="scope.row.disabled" @click="handleRun(scope.row)" type="text" size="small">启动</el-button>
        </template>
      </el-table-column>
      <el-table-column v-loading="loading1" type="expand" width="1">
        <template slot-scope="scope">
          <el-tabs type="border-card" v-model="detailList['device_' + scope.row.id].defaultTabsName">
            <el-tab-pane name="realTimeStatusRecord">
              <span slot="label">实时状态</span>
              <real-time-status :info="scope.row"></real-time-status>
            </el-tab-pane>
            <el-tab-pane name="pastDayRecord">
              <span slot="label">过去24小时状态</span>
              <status-echarts
                v-if="
                  detailList['device_' + scope.row.id].defaultTabsName ===
                    'pastDayRecord'
                "
                :info="scope.row"
                type="1"
              ></status-echarts>
            </el-tab-pane>
            <el-tab-pane name="pastWeekRecord">
              <span slot="label">过去7天状态</span>
              <status-echarts
                v-if="
                  detailList['device_' + scope.row.id].defaultTabsName ===
                    'pastWeekRecord'
                "
                :info="scope.row"
                type="2"
              ></status-echarts>
            </el-tab-pane>
            <el-tab-pane name="pastMonthRecord">
              <span slot="label">过去30天状态</span>
              <status-echarts
                v-if="
                  detailList['device_' + scope.row.id].defaultTabsName ===
                    'pastMonthRecord'
                "
                :info="scope.row"
                type="3"
              ></status-echarts>
            </el-tab-pane>
            <el-tab-pane name="malfunctionRecord">
              <span slot="label">故障记录</span>
              <broken-record
                v-if="
                  detailList['device_' + scope.row.id].defaultTabsName ===
                    'malfunctionRecord'
                "
                :info="scope.row"
              ></broken-record>
            </el-tab-pane>
            <el-tab-pane name="moreInfoRecord">
              <span slot="label">更多信息</span>
              <more-info
                v-if="
                  detailList['device_' + scope.row.id].defaultTabsName ===
                    'moreInfoRecord'
                "
                :info="scope.row"
              ></more-info>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-sizes="[10, 50, 100]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 位置 -->
    <multifunction-dialog v-if="dialogLocaltion" :parames="multifunctionDialogparames" @close="dialogLocaltion = false"></multifunction-dialog>
    <el-dialog
      title="梯控"
      width="600px"
      top="10vh"
      v-dialogDrag
      v-if="elevatorVisible"
      :close-on-click-modal="false"
      :visible.sync="elevatorVisible"
      @close="hideElevator()"
    >
      <elevator-form :hideElevator="hideElevator" :singleData="singleData"></elevator-form>
    </el-dialog>
  </div>
</template>
<script>

import util from '@/utils/util'
import {
  getFcfRealTimeStatusCountOverview,
  getFcfStatusList,
  getSysFcfCategoryTree,
  getMockEquips
} from '@/api/fcf'
import { getFbsTree } from '@/api/fbs'
import { getAlarmFcfMoreInfo } from '@/api/alarm'
import TreeSelect from '@/libs/TreeSelect/Main'
import { getOrgList } from '@/api/org'
import { updateElevatorCon } from '@/api/common'
import RealTimeStatus from './PageModel/RealTimeStatus'
import StatusEcharts from './PageModel/StatusEcharts'
import BrokenRecord from './PageModel/BrokenRecord'
import MoreInfo from './PageModel/MoreInfo'
import MultifunctionDialog from '../MultifunctionDialog/Main'
import ElevatorForm from './Dialog/ElevatorForm'

export default {
  name: 'EquipLink',
  components: {
    TreeSelect,
    RealTimeStatus,
    StatusEcharts,
    BrokenRecord,
    MoreInfo,
    MultifunctionDialog,
    ElevatorForm,
  },
  data() {
    return {
      loading: false,
      loading1: false,
      orgOptions: [
        {
          organizationId: this.$store.state.userinfo.organizationIds,
          shortName: '全部业主单位',
        },
      ],
      // 消防系统-资产类别
      typeList: [],
      typeDefaultProps: {
        children: 'fireCtlFacsCategoryList',
        label: 'name',
        value: 'id',
      },
      typeNodeKey: 'id',
      defaultCheckedCategoryId: [],
      // 建筑物
      buildList: [],
      buildDefaultProps: {
        children: 'nodes',
        label: 'text',
        value: 'id',
      },
      buildNodeKey: 'id',
      defaultCheckedFbsId: [],
      // 搜索
      searchForm: {
        orgIds: this.$store.state.userinfo.organizationIds,
        systemId: '-1',
        fcfCategoryId: '',
        fbsId: 0,
        name: '',
        fireTType: '-1',
      },
      // 设备统计
      equipmentStatistics: {
        fireAlarmCount: 0,
        faultAlarmCount: 0,
        count: 0,
        shieldAlarmCount: 0,
        linkageAlarmCount: 0,
        normalCount: 0,
      },
      // 列表
      tableData: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 展开详情
      defaultTabsName: 'realTimeStatusRecord',
      detailList: {},
      dialogLocaltion: false,
      multifunctionDialogparames: {},
      elevatorVisible: false, // 梯控弹框是否可见
      singleData: {},
      buildNode: 1,
      mockEquips:[]
    }
  },
  created() {
    let that = this
    // 绑定下拉框
    if (this.$store.state.userinfo.isMuilUnitUser === 1) {
      getOrgList({ queryType: 0 }).then((res) => {
        that.orgOptions.push.apply(this.orgOptions, res.data)
      })
    } else {
      that.getBuildList()
    }
    that.getTypeList()
    let { refreshEquipLink } = this.$route.params
    if (typeof refreshEquipLink == 'undefined') {
      this.getStatic()
      getMockEquips().then(res=>{
        this.mockEquips=res.data
        this.runDuration=res.duration
        this.getTableData()
      })
    }
  },
  activated() {
    let { name, refreshEquipLink } = this.$route.params
    if (typeof refreshEquipLink != 'undefined') {
      this.searchForm.name = name || ''
      this.getStatic()
      getMockEquips().then(res=>{
        this.mockEquips=res.data
        this.runDuration=res.duration
        this.getTableData()
      })
    }
  },
  methods: {
    handleRun(row){
      row.disabled=true
      let item=this.mockEquips.find(n=>{ return n.id==row.id })
      fetch(item.url)
      setTimeout(()=>{
        row.disabled=false
      },this.runDuration||5000)
    },
    handleCommand(command) {
      switch (command) {
        case 'export':
          this.handleExport()
          break
        default:
          break
      }
    },
    handleExport() {
      if (this.searchForm.orgIds.toString().indexOf(',') > -1) {
        return this.$message.warning('请选择一个业主单位')
      }
      // window.open(this.GLOBAL.baseURL)
    },
    /* 处理梯控 */
    handleElevator(val) {
      this.singleData = val
      this.elevatorVisible = true
    },
    hideElevator(row) {
      if (typeof row === 'object') {
        updateElevatorCon(row).then((res) => {
          if (res.status === 200) {
            this.$message.success('保存成功！')
            this.search()
          } else {
            this.$message.error(res.info)
          }
        })
      }
      this.elevatorVisible = false
    },
    // 获取消防系统与设备类别
    getTypeList() {
      let that = this
      getSysFcfCategoryTree({
        orgIds:
          that.searchForm.orgIds || that.$store.state.userinfo.organizationIds,
      }).then((res) => {
        // 加上全部
        res.data.unshift({
          id: '-1',
          name: '全部物联设备类别',
        })
        that.typeList = res.data
        // 默认选择全部
        that.$nextTick(() => {
          that.defaultCheckedCategoryId = ['-1']
        })
      })
    },
    // 消防系统与设备类别树被点击
    handleNodeClick(obj, node, item) {
      let that = this
      if (obj.hasOwnProperty('parentId')) {
        // 记录系统id和设备类别id
        that.searchForm.systemId = node.parent.data.id || ''
        that.searchForm.fcfCategoryId = obj.id
      } else {
        // 记录系统id和设备类别id
        that.searchForm.systemId = obj.id
        that.searchForm.fcfCategoryId = ''
      }
      that.search()
    },
    // 获取建筑物数据
    getBuildList() {
      let that = this
      getFbsTree({
        organizationId:
          that.searchForm.orgIds || that.$store.state.userinfo.organizationIds,
      }).then((res) => {
        that.buildList = res.data
      })
    },
    // 获取统计信息
    getStatic() {
      let that = this
      let parames = {
        orgIds: that.searchForm.orgIds,
        name: that.searchForm.name.trim(),
        fireSystemId: that.searchForm.systemId || '',
        categoryId: that.searchForm.fcfCategoryId || '',
        fbsId: that.searchForm.fbsId || 0,
        fireTTypes: -1,
      }
      getFcfRealTimeStatusCountOverview(parames).then((res) => {
        this.equipmentStatistics = res.data
      })
    },
    // 获取列表数据
    getTableData(pageIndex, pageSize) {
      let that = this
      that.loading = true
      if (pageIndex) {
        that.currentPage = pageIndex
      }
      if (pageSize) {
        that.pageSize = pageSize
      }
      if (that.searchForm.fbsId) {
        this.buildNode = 1
      } else {
        this.buildNode = 0
      }
      let parames = {
        orgIds: that.searchForm.orgIds,
        fbsId: that.searchForm.fbsId || 0,
        name: that.searchForm.name.trim(),
        systemId: that.searchForm.systemId || '',
        fcfCategoryId: that.searchForm.fcfCategoryId || '',
        fireTType: that.searchForm.fireTType,
        pageSize: that.pageSize,
        pageIndex: that.currentPage - 1,
        queryFbsType: this.buildNode,
      }
      getFcfStatusList(parames).then((res) => {
        that.tableData = res.data.map(n=>{
          n.disabled=false
          return n
        })
        that.total = res.total
        that.loading = false
      })
    },
    handleSizeChange(pageSize) {
      this.getTableData(1, pageSize)
    },
    handleCurrentChange(currentPage) {
      this.getTableData(currentPage)
    },
    // 查询
    search() {
      this.getStatic()
      this.getTableData(1)
    },
    // 单位切换
    orgIdChange() {
      this.searchForm.fbsId = 0
      this.defaultCheckedFbsId = []
      // 如果是多个单位，不用查询建筑物
      if (String(this.searchForm.orgIds).split(',').length === 1) {
        this.getBuildList()
      } else {
        this.buildList = []
      }
      this.search()
    },
    // 打开位置定位
    openPosition(row) {
      let that = this
      that.dialogLocaltion = true
      that.multifunctionDialogparames = {
        fcfName: row.name,
        fcfId: row.id,
      }
    },
    // 打开附件的监控
    openMonitor(row, videoItem) {
      util.rowShowVedio(
        {
          fcFacilitiesId: row.id,
          organizationId: row.organizationId,
          serverId: row.serverId,
        },
        0,
        videoItem
      )
    },
    // 展开详情
    handleDetail(row) {
      let that = this

      if (row && !that.detailList.hasOwnProperty('device_' + row.id)) {
        let obj = {
          defaultTabsName: 'realTimeStatusRecord',
          brokenRecord: {},
          moreInfo: {},
        }

        that.$set(that.detailList, 'device_' + row.id, obj)

        // 获取维保记录
        // Dao.getMaintainRecordsByAssetsId({
        //     assetsId: row.id,
        //     pageIndex: 0,
        //     pageSize: 5
        // }).then(res => {
        //    that.$set(that.maintainRecords, 'device_' + row.id, res.data)
        // })

        // 获取更多信息
        // Dao.getAInfo({
        //     id: row.id
        // }).then(res => {
        //     that.assetInfo = res.data
        // })
      }
      this.$refs.equipmentThingsTableList.toggleRowExpansion(row)
    },
    // 更多信息
    getMoreInfo(id) {
      getAlarmFcfMoreInfo({ fcfId: id }).then((res) => {
        //TODO
      })
    },
  },
  watch: {
    fireTTypeSelect(val, oldVal) {
      if (val !== oldVal) {
        this.getTableData(1)
      }
    },
    fbsIdSelect(val, oldVal) {
      if (val && val !== oldVal) {
        this.search()
      }
    },
  },
  computed: {
    fireTTypeSelect() {
      return this.searchForm.fireTType
    },
    fbsIdSelect() {
      return this.searchForm.fbsId
    },
  },
}
</script>

<style lang="scss" scoped>
.search-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/deep/ .el-tag {
  .el-button {
    span {
      text-decoration: underline;
    }
  }
}
</style>
